package com.my.concurrency.basic.example.atomatic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 原子类使用
 *
 * @author: mars
 * @date: 2023-03-03 1:56 PM
 */
public class CountAtomicIntegerTest {
    private final AtomicInteger counter = new AtomicInteger(0);

    private void add10k() {
        int idx = 0;
        while (idx++ < 10000) {
            counter.getAndIncrement();
        }
    }

    public static long calc() {
        CountAtomicIntegerTest test = new CountAtomicIntegerTest();
        Thread th1 = new Thread(test::add10k);
        Thread th2 = new Thread(test::add10k);

        th1.start();
        th2.start();

        try {
            th1.join();
            th2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return test.counter.get();
    }

    public static void main(String[] args) {
        // 使用原子类，不管执行多少次，都是2000
        System.out.println("The result is : " + CountAtomicIntegerTest.calc());
    }
}
